import json
import os
import time

from .leetcode_operation import LeetCodeOperation


class ProblemsetQuestionList(LeetCodeOperation):
    def __init__(self, requests_manager, base_url="https://leetcode.cn", **params):
        super().__init__(requests_manager, base_url)
        self.params = params.get('params')
        self.filename="problemset_questions.json"
        self.endpoint = 'graphql'

    def generate_payload(self):
        query_string = """
        query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {
          problemsetQuestionList(
            categorySlug: $categorySlug
            limit: $limit
            skip: $skip
            filters: $filters
          ) {
            hasMore
            total
            questions {
              acRate
              difficulty
              freqBar
              frontendQuestionId
              isFavor
              paidOnly
              solutionNum
              status
              title
              titleCn
              titleSlug
              topicTags {
                name
                nameTranslated
                id
                slug
              }
              extra {
                hasVideoSolution
                topCompanyTags {
                  imgUrl
                  slug
                  numSubscribed
                }
              }
            }
          }
        }
        """
        return {
            "query": query_string,
            "variables": self.params,
            "operationName": "problemsetQuestionList"
            }
    def parse_graphql_data(self, data):
        questions_data = data.get('data', {}).get('problemsetQuestionList', {}).get('questions', [])
        # parsed_questions = []

        # for question in questions_data:
        #     parsed_question = {
        #         key: question.get(key) for key in ['acRate', 'difficulty', 'freqBar', 'frontendQuestionId', 'isFavor', 'paidOnly', 'solutionNum', 'status', 'title', 'titleCn', 'titleSlug']
        #     }
        #     parsed_question['topicTags'] = [{key: tag.get(key) for key in ['name', 'nameTranslated', 'id', 'slug']} for tag in question.get('topicTags', [])]
        #     parsed_question['topCompanyTags'] = [{key: company_tag.get(key) for key in ['imgUrl', 'slug', 'numSubscribed']} for company_tag in question.get('extra', {}).get('topCompanyTags', [])]
            
        #     parsed_questions.append(parsed_question)

        return questions_data


    def fetch_all_data(self, folder_name="ProblemsetQuestionList", request_interval=1):
        all_data = []
        skip = 0
        has_more = True
        limit=100
        os.makedirs(os.path.join(self.directory, folder_name), exist_ok=True)
        

        while has_more:
            self.params.update({'skip': skip, 'limit': limit})
            data = self.fetch_data(self.endpoint, method='POST')
            total = data.get('data', {}).get('problemsetQuestionList', {}).get('total', 0)
            download_total = len(os.listdir(os.path.join(self.directory, folder_name)))
            if download_total >= total:
                return os.listdir(os.path.join(self.directory, folder_name))

            questions = self.parse_graphql_data(data)
            for question in questions:
                slug = question.get('titleSlug')
                self.filename = f"{slug}.json"
                self.logger.debug(f'save: {self.filename}')
                if not os.path.exists(os.path.join(self.directory, folder_name, self.filename)):
                    self.save_json(question, os.path.join(folder_name, self.filename))

            has_more = data.get('data', {}).get('problemsetQuestionList', {}).get('hasMore', False)
            skip += limit
            self.logger.info(f"skip: {skip}")
            # time.sleep(request_interval)

        # self.save_json(all_data, self.filename)
        return os.listdir(os.path.join(self.directory, folder_name))


    def execute(self):
        data = self.fetch_data(self.endpoint, method='POST')
        data = self.parse_graphql_data(data)
        self.save_json(data, self.filename)